﻿using StuWebApi.Dto;
using StuWebApi.Entity;

namespace StuWebApi.Middleware;

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, ApplicationDbContext dbContext)
    {
        // Before the request
        var startedAt = DateTime.UtcNow;

        try
        {
            // Execute the request
            await _next(context);
        }
        finally
        {
            // After the request
            var finishedAt = DateTime.UtcNow;
            var log = new Log
            {
                Timestamp = finishedAt,
                Action = $"{context.Request.Method} {context.Request.Path}",
                Description = $"Status code: {context.Response.StatusCode}, Request took: {finishedAt - startedAt}"
            };

            // Save the log to the database
            dbContext.Logs.Add(log);
            await dbContext.SaveChangesAsync();
        }
    }
}

